﻿using BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UI
{
    public partial class DeptForm : Form
    {
        private BLL.DepartmentService departmentService;

        public DeptForm()
        {
            departmentService = new BLL.DepartmentService();
            InitializeComponent();
        }

        private void dataTableInit()
        {
            List<Department> list = departmentService.list(new BLL.Department());
            department_list_box.DataSource = list;
            department_list_box.DisplayMember = "DepartmentName";
            department_list_box.ValueMember = "DepartmentName";
        }

        private void DeptForm_Load(object sender, EventArgs e)
        {
            dataTableInit();
        }

        // 新增部门
        private void button1_Click(object sender, EventArgs e)
        {
            // 验证数据
            if (dept_text_box.Text == "")
            {
                MessageBox.Show("请填写完整表单信息!");
            }
            else
            {
                // 填入表单数据
                Department department = new Department(
                    Convert.ToInt32(departmentService.getMaxId() + 1),
                   dept_text_box.Text,
                    0
                    );
                // 判断同名的部门是否存在
                List<Department> list = departmentService.list(department);
                if (list.Count > 0)
                {
                    MessageBox.Show("该部门已经存在！");
                    return;
                }
                bool res = departmentService.save(department);
                if (res)
                {
                    MessageBox.Show("新增成功!");
                    // 初始化表格数据
                    dataTableInit();
                    // 表格清空
                    dept_text_box.Text = null;
                }
                else
                {
                    MessageBox.Show("新增失败!");
                }
            }

        }


        // 右击 删除事件
        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 获取选定的元素
            Department department = (Department)department_list_box.SelectedItem;
            if (department != null)
            {
                bool flag = departmentService.deleteById(department.DepartmentID);
                if (flag)
                {
                    MessageBox.Show("删除成功！");
                    dataTableInit();
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            else
            {
                MessageBox.Show("选中的部门不存在或者已经删除了！");
            }
        }
    }
}
